<!--
 * @Author: Bennty
 * @Date: 2024-08-27 15:32:32
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2024-10-23 16:19:00
 * @Description: 请填写简介
-->
<template>
    <el-dialog :model-value="props.visible" title="下包装订单" width="45%" destroy-on-close @close="handleClose">
        <el-form :model="formData" ref="formRef" label-width="auto">
            <el-form-item label="交货日期" prop="deliveryDate" label-position="right">
                <el-date-picker v-model="formData.deliveryDate" placeholder="年/月/日" value-format="YYYY-MM-DD"></el-date-picker>
            </el-form-item>
            <el-form-item label="包装件名称" label-position="right">
                <span>{{ `${props.data.productCategoriesName}-${props.data.productSubcategoryName}-${props.data.specsDetail}` }}</span>
            </el-form-item>
            <el-form-item label="包装物信息">
                <el-form-item label="包装袋:" style="width: 100%">
                    <el-row style="width: 100%">
                        <el-col :span="8">
                            <span>{{ `小类：` }}</span>
                            <span class="pacakage-info">{{ packageBag?.subclassName || '无' }}</span>
                        </el-col>
                        <el-col :span="8">
                            <span>{{ `品名：` }}</span>
                            <span class="pacakage-info">{{ packageBag?.subclassName || '无' }}</span>
                        </el-col>
                        <el-col :span="8"></el-col>
                    </el-row>
                </el-form-item>
                <el-form-item v-for="(item,index) in packageItems" :key="index" :label="`包装物${index+1}:`" style="width: 100%">
                    <el-row style="width: 100%">
                        <el-col :span="8">
                            <span>{{ `小类：` }}</span>
                            <span class="pacakage-info">{{ item.subType || ''}}</span>
                        </el-col>
                        <el-col :span="8">
                            <span>{{ `品名：` }}</span>
                            <span class="pacakage-info">{{ item.auxiliry || ''}}</span>
                        </el-col>
                        <el-col :span="8">
                            <span>{{ `数量：` }}</span>
                            <span class="pacakage-info">{{ item.number}}</span>
                        </el-col>
                    </el-row>
                </el-form-item>
            </el-form-item>
            <el-form-item label="生产数量" prop="produceNumber" label-position="right">
                <el-input type="number" v-model.number="formData.produceNumber" placeholder="请输入" />
            </el-form-item>
            <el-form-item label="备注" prop="remark" label-position="right">
                <el-input v-model="formData.remark" type="textarea" maxlength="125" show-word-limit />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button  type="primary" @click="handleSubmit" >确 定</el-button>
                <el-button @click="handleClose">取 消</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import type { FormInstance } from 'element-plus';
import { getSingleByTotalApi } from '@/api/sj/warehouse/typeManagement';
import { getAuxiliaryByTypeApi, addPackagingOrderApi } from '@/api/sj/warehouse/auxiliary';

const props = defineProps(['visible', 'data', 'types','packageData']);
const emits = defineEmits(['close','submit']);
const formRef = ref<FormInstance>();
const formData = ref({
    deliveryDate: undefined,
    produceNumber: undefined,
    remark: undefined
});

const packageBag = ref<any>();
const packageItems = ref<any[]>([]);

const getSingleType = async (majorType: any) => {
    const { data } = await getSingleByTotalApi(majorType);
    return data;
};

const getAuxilary = async (major: any, sub: any) => {
    const { data } = await getAuxiliaryByTypeApi(major, sub);
    return data;
};

/** 获取包装袋信息 */
watch(()=>props.packageData, (newValue)=>{
    if(newValue.packingSubcategoryType){
        getSingleType('auxiliary_material_packing').then((result)=>{
            const packageBagData = result.filter((item:any)=>item.subclassType ==newValue.packingSubcategoryType )[0];
            packageBag.value = packageBagData;
        });
    };
},{deep: true});


/** 获取包装件信息 */
// watch(()=>props.packageData, async (newValue)=>{
//     if(newValue.packingList.length > 0){
//         let packageItemList :any[] = [];
//         newValue.packingList.forEach((item:any)=>{
//             const majorType = props.types.filter((type:any)=>type.majorType == item.productCategoriesType)[0];
//             const mession = [getSingleType(item.productCategoriesType), getAuxilary(item.productCategoriesType, item.productSubcategoryType)];
//             Promise.all(mession).then(([typeRsult, auxiliaryResult])=>{
//                 // console.log(typeRsult, auxiliaryResult);
//                 const subData = typeRsult.filter((type:any)=>type.subclassType == item.productSubcategoryType)[0];
//                 const auxilaryData = auxiliaryResult.filter((auxiliary:any)=>auxiliary.id == item.joinAuxiliaryId)[0];
//                 const data = {
//                     majorType: majorType.majorName || '',
//                     subType: subData?.subclassName || '',
//                     auxiliry: auxilaryData?.specsDetail || '',
//                     number: item.number
//                 };
//                 packageItemList.push(data);
//             });
//         });
//         packageItems.value = packageItemList;
//         console.log('packageItemList',packageItemList);
//         console.log(packageItems.value);
//     };
// },{deep: true})

watch(
    () => props.packageData,
    async (newValue) => {
        if (newValue.packingList.length > 0) {
        let packageItemList: any[] = [];
        for (const item of newValue.packingList) {
            const majorType = props.types.filter(
                (type: any) => type.majorType == item.productCategoriesType
            )[0];
            const mission = [
                getSingleType(item.productCategoriesType),
                getAuxilary(item.productCategoriesType, item.productSubcategoryType),
            ];
            
            try {
                const [typeResult, auxiliaryResult] = await Promise.all(mission);

                const subData = typeResult.filter(
                    (type: any) => type.subclassType == item.productSubcategoryType
                )[0];
                const auxilaryData = auxiliaryResult.filter(
                    (auxiliary: any) => auxiliary.id == item.joinAuxiliaryId
                )[0];

                const data = {
                    majorType: majorType?.majorName || '',
                    subType: subData?.subclassName || '',
                    auxiliry: auxilaryData?.specsDetail || '',
                    number: item.number,
                };
                packageItemList.push(data);
            } catch (error) {
                console.error('Error in fetching data: ', error);
            }
        }
            packageItems.value = packageItemList;
            // console.log("packageItemList", packageItemList);
            // console.log(packageItems.value);
        }
    },
    { deep: true }
);

const handleSubmit = async () => {
    const submitData = {
        ...formData.value,
        auxiliaryId: props.data.id,
        packingName: `${props.data.productCategoriesName}-${props.data.productSubcategoryName}-${props.data.specsDetail}包装件订单${Date.now()}`
    };
    const {code} = await addPackagingOrderApi(submitData);
    if(code == 200){
        emits('submit', true);
    }else{
        emits('submit', false);
    }
};

const handleClose = ()=>{
    emits('close');
    formRef.value?.resetFields();
    packageItems.value = [];
};
</script>

<style lang="scss" scoped>
.pacakage-info{
    color: var(--el-color-primary);
}
.dialog-footer{
    display: flex;
    justify-content: center;
}
</style>